package com.vision.service.impl;

import com.vision.common.bean.CommonResult;
import com.vision.common.bean.install.InstallOrder;
import com.vision.common.bean.requestlog.RequestLogOrder;
import com.vision.common.util.BeanUtils;
import com.vision.common.util.Validator;
import com.vision.dao.InstallDao;
import com.vision.dao.RequestLogDao;
import com.vision.entity.install.Install;
import com.vision.entity.requestlog.RequestLog;
import com.vision.service.CommonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Filename CommonServiceImpl.java
 * @Description
 * @Version 1.0
 * @Author zhongc
 * @Email zhong_ch@foxmail.com
 * @History <li>Author: zhongc</li>
 * <li>Date: 2017/5/29</li>
 * <li>Version: 1.0</li>
 * <li>Content: create</li>
 */
@Service
public class CommonServiceImpl implements CommonService {

    public static final Logger LOGGER = LoggerFactory.getLogger(CommonServiceImpl.class);

    @Resource
    private InstallDao installDao;

    @Resource
    private RequestLogDao requestLogDao;

    @Override
    public CommonResult install(InstallOrder request) {
        CommonResult result = new CommonResult();
        try {
            Install install = BeanUtils.copyProperties(request, Install.class);
            if (install.getDate() == null) {
                install.setDate(new Date());
            }
            installDao.insertSelective(install);
        } catch (Exception e) {
            LOGGER.error("CommonService.install error:{}", e);
            result.setSuccess(false);
            result.setDesc("未知错误");
        }
        return result;
    }

    @Override
    public CommonResult requestLog(RequestLogOrder request) {
        CommonResult result = new CommonResult();
        try {
            Validator.validate(request);
            RequestLog requestLog = BeanUtils.copyProperties(request, RequestLog.class);
            if (requestLog.getRequestDate() == null) {
                request.setRequestDate(new Date());
            }
            requestLogDao.insertSelective(requestLog);
        } catch (IllegalArgumentException e) {
            LOGGER.warn("CommonService.install error:{}", e);
            result.setSuccess(false);
            result.setDesc("请求参数错误");
        } catch (Exception e) {
            LOGGER.error("CommonService.install error:{}", e);
            result.setSuccess(false);
            result.setDesc("未知错误");
        }
        return result;
    }
}
